package com.tongguan.paypos.utils;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by Joylive on 2016/9/12 .
 */
public class AppUtils {

    /**
     * @param context
     * @param packageName
     * @return 获取应用名称
     */
    public static String getAppName(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        String appName = null;
        try {
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
            appName = (String) packageManager.getApplicationLabel(applicationInfo);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return appName;
    }


    //
    public static boolean isCallable(Context context,Intent intent) {
        List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    /**
     * @param context
     * @param packageName
     * @return 获取应用图标
     */
    public static Drawable getAppIcon(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        Drawable loadIcon = null;
        try {
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
            loadIcon = applicationInfo.loadIcon(packageManager);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return loadIcon;
    }

    /**
     * @param context
     * @param packageName
     * @return 获取应用更新时间
     */
    public static long getAppDate(Context context, String packageName) {
        long lastUpdateTime = 0;
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
            lastUpdateTime = packageInfo.lastUpdateTime;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return lastUpdateTime;
    }

    /**
     * @param context
     * @param packageName
     * @return 获取应用大小
     */
    public static long getAppSize(Context context, String packageName) {
        long appSize = 0;
        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
            appSize = new File(applicationInfo.sourceDir).length();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appSize;
    }

    /**
     * @param context
     * @param packageNam
     * @return 获取应用
     */
    public static String getApp(Context context, String packageNam) {
        return context.getPackageResourcePath();
    }

    /**
     * @param context
     * @param packageName
     * @return 获取应用版本名称
     */
    public static String getAppVersionName(Context context, String packageName) {
        String appVersionNmae = null;
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
            appVersionNmae = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appVersionNmae;
    }

    /**
     * @param context
     * @param packageName
     * @return 获取应用版本号
     */
    public static int getAppVersionCode(Context context, String packageName) {
        int appVersionCode = 0;
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
            appVersionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appVersionCode;
    }


    /**
     * @param context
     * @param packageName
     * @return 获取应用的安装市场
     */
    public static String getAppInstallerPackName(Context context, String packageName) {
        return context.getPackageManager().getInstallerPackageName(packageName);
    }

    /**
     * @return 获取Cpu内核数
     */
    public static int getNumCores() {

        try {
            File dir = new File("/sys/devices/system/cpu/");
            File[] files = dir.listFiles(new FileFilter() {

                @Override
                public boolean accept(File pathname) {
                    return Pattern.matches("cpu[0-9]", pathname.getName());
                }
            });
            return files.length;
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }


    /**
     * @param context
     * @return 获得root权限
     */
    public static boolean getRootPermission(Context context) {
        String packageCodePath = context.getPackageCodePath();
        Process process = null;
        DataOutputStream os = null;
        try {
            String cmd = "chmod 777 " + packageCodePath;
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }


    /**
     * @param context
     * @param permission
     * @return 是否有权限
     */
    public static boolean hasPermission(Context context, String permission) {
        if (context != null && !TextUtils.isEmpty(permission)) {
            try {
                PackageManager packageManager = context.getPackageManager();
                if (packageManager != null) {
                    if (PackageManager.PERMISSION_GRANTED == packageManager.checkPermission(permission, context
                            .getPackageName())) {
                        return true;
                    }
                    Log.d("AppUtils", "Have you  declared permission " + permission + " in AndroidManifest.xml ?");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    /**
     * @param context
     * @param packageName
     * @return 应用是否安装
     */
    public static boolean isInstalled(Context context, String packageName) {
        boolean installed = false;
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }
        List<ApplicationInfo> list = context.getPackageManager().getInstalledApplications(0);
        for (ApplicationInfo info : list) {
            if (packageName.equals(info.packageName)) {
                installed = true;
                break;
            }
        }
        return installed;
    }

    /**
     * @param context
     * @param filePath
     * @return 安装应用
     */
    public static boolean installApk(Context context, String filePath) {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile() || file.length() <= 0) {
            return false;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        return true;
    }

    /**
     * @param context
     * @param packageName
     * @return 卸载应用
     */
    public static boolean unInstallApk(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_DELETE, Uri.parse("package://" + packageName));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        return true;
    }


    /**
     * @param context
     * @param packageName
     * @return 是否是系统应用
     */
    public static boolean isSystemApp(Context context, String packageName) {
        boolean isSystem = false;

        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
            if (applicationInfo != null && (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) > 0) {
                isSystem = false;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();

        }
        return isSystem;
    }


    /**
     * @param context
     * @param className
     * @return 是否开启服务
     */
    public static boolean isServiceRunning(Context context, String className) {
        boolean isRunning = false;

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE);
        for (RunningServiceInfo rsi : serviceList) {
            if (className.equals(rsi.service.getClassName())) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    /**
     * @param context
     * @param className
     * @return 停止服务
     */
    public static boolean stopRunningService(Context context, String className) {
        Intent intent_service = null;
        boolean isStop = false;
        try {
            intent_service = new Intent(context, Class.forName(className));
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (intent_service != null) {
            isStop = context.stopService(intent_service);
        }

        return isStop;
    }

    /**
     * @param context
     * @param pid
     * @param processName 结束进程
     */
    public static void killProcesses(Context context, int pid, String processName) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String packageName;
        try {
            if (!processName.contains(":")) {
                packageName = processName;
            } else {
                packageName = processName.split(":")[0];
            }
            activityManager.killBackgroundProcesses(packageName);
            Method forceStopPackage = activityManager.getClass().getDeclaredMethod("forceStopPackage", String.class);
            forceStopPackage.setAccessible(true);
            forceStopPackage.invoke(activityManager, packageName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param script
     * @return 运行进程
     */
    public static String runScript(String script) {
        String sRet;
        try {
            final Process m_process = Runtime.getRuntime().exec(script);
            final StringBuilder sbread = new StringBuilder();
            Thread tout = new Thread(new Runnable() {
                public void run() {
                    BufferedReader bufferedReader = new BufferedReader(
                            new InputStreamReader(m_process.getInputStream()),
                            8192);
                    String ls_1;
                    try {
                        while ((ls_1 = bufferedReader.readLine()) != null) {
                            sbread.append(ls_1).append("\n");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            tout.start();

            final StringBuilder sberr = new StringBuilder();
            Thread terr = new Thread(new Runnable() {
                public void run() {
                    BufferedReader bufferedReader = new BufferedReader(
                            new InputStreamReader(m_process.getErrorStream()),
                            8192);
                    String ls_1;
                    try {
                        while ((ls_1 = bufferedReader.readLine()) != null) {
                            sberr.append(ls_1).append("\n");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            terr.start();

            m_process.waitFor();
            while (tout.isAlive()) {
                Thread.sleep(50);
            }
            if (terr.isAlive())
                terr.interrupt();
            String stdout = sbread.toString();
            String stderr = sberr.toString();
            sRet = stdout + stderr;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return sRet;
    }

    /**
     * @param context
     * @param packageName 启动应用(通过包名)
     */
    public static void runApp(Context context, String packageName) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        if (intent == null) {
           Toast.makeText(context, "APP未安装，请先下载安装应用", Toast.LENGTH_SHORT).show();
            //跳转应用市场下载
        }else{
            context.startActivity(intent);
        }
    }

    /**
     * @param context
     * @param action
     * @param bundle 启动应用(通过Action)
     */
    public static void runApp(Context context, String action, Bundle bundle) {
        Intent intent = new Intent(action);
        List<ResolveInfo> resolveIfs = context.getPackageManager().queryIntentActivities(intent, 0);
        if (resolveIfs.size() > 0 ) {
            if (bundle!=null){
                intent.putExtras(bundle);
            //    L.d("Bundle", "runApp: "+ bundle.toString());
            }
            context.startActivity(intent);
        }else{
            Toast.makeText(context, "APP未安装，请先下载安装应用", Toast.LENGTH_SHORT).show();
            //跳转应用市场下载
        }
    }
    /**
     * @param context
     * @param action
     * @param bundle 启动应用(通过Action)
     * @param request
     */
    public static void runApp(AppCompatActivity context, String action, Bundle bundle, int request) {
        Intent intent = new Intent(action);
        List<ResolveInfo> resolveIfs = context.getPackageManager().queryIntentActivities(intent, 0);
        if (resolveIfs.size() > 0 ) {
            if (bundle!=null){
                intent.putExtras(bundle);
              //  L.d("Bundle", "runApp: "+ bundle.toString());
            }
            context.startActivityForResult(intent,request);
        }else{
            Toast.makeText(context, "APP未安装，请先下载安装应用", Toast.LENGTH_SHORT).show();
            //跳转应用市场下载
        }
    }

    public static void runComponent(Context context,String packageName,String launchAct,Bundle bundle){
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(packageName,launchAct));
        List<ResolveInfo> resolveIfs = context.getPackageManager().queryIntentActivities(intent, 0);
        if (resolveIfs.size() > 0 ) {
            if (bundle!=null){
                intent.putExtras(bundle);
                //    L.d("Bundle", "runApp: "+ bundle.toString());
            }
            context.startActivity(intent);
        }else{
            Toast.makeText(context, "APP未安装，请先下载安装应用", Toast.LENGTH_SHORT).show();
            //跳转应用市场下载
        }
    }

    public static void runComponent(AppCompatActivity context,String packageName,String launchAct,Bundle bundle,int request){
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(packageName,launchAct));
        List<ResolveInfo> resolveIfs = context.getPackageManager().queryIntentActivities(intent, 0);
        if (resolveIfs.size() > 0 ) {
            if (bundle!=null){
                intent.putExtras(bundle);
                //    L.d("Bundle", "runApp: "+ bundle.toString());
            }
            context.startActivityForResult(intent,request);
        }else{
            Toast.makeText(context, "APP未安装，请先下载安装应用", Toast.LENGTH_SHORT).show();
            //跳转应用市场下载
        }
    }


    public static void runComponent(AppCompatActivity context, Fragment fragment,String packageName,String launchAct,Bundle bundle,int request){
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(packageName,launchAct));
        List<ResolveInfo> resolveIfs = context.getPackageManager().queryIntentActivities(intent, 0);
        if (resolveIfs.size() > 0 ) {
            if (bundle!=null){
                intent.putExtras(bundle);
                //    L.d("Bundle", "runApp: "+ bundle.toString());
            }
            fragment.startActivityForResult(intent,request);
        }else{
            Toast.makeText(context, "APP未安装，请先下载安装应用", Toast.LENGTH_SHORT).show();
            //跳转应用市场下载
        }
    }

    /**
     * @param context
     * @param action
     * @param bundle 启动应用(通过Action)
     * @param request
     */
    public static void runFrm2App(AppCompatActivity context, Fragment fragment, String action, Bundle bundle, int request) {
        Intent intent = new Intent(action);
        List<ResolveInfo> resolveInfos = context.getPackageManager().queryIntentActivities(intent, 0);
        if (resolveInfos.size() > 0 ) {
            if (bundle!=null){
                intent.putExtras(bundle);
                //  L.d("Bundle", "runApp: "+ bundle.toString());
            }
            fragment.startActivityForResult(intent,request);
        }else{
            Toast.makeText(context, "APP未安装，请先下载安装应用", Toast.LENGTH_SHORT).show();
            //跳转应用市场下载
        }
    }


//    public static void cleanCache(Context context) {
//        FileUtils.deleteFileByDirectory(context.getCacheDir());
//    }
//
//    public static void cleanDatabases(Context context) {
//        String filepath = String.format(String.format(context.getFilesDir().getParent() + File.separator + "%s", "databases"));
//        FileUtils.deleteFileByDirectory(new File(filepath));
//    }
//
//    public static void cleanSharedPreference(Context context){
//        String filepath = String.format(String.format(context.getFilesDir().getParent() + File.separator + "%s", "shared_prefs"));
//        FileUtils.deleteFileByDirectory(new File(filepath));
//    }


}
